package 如何优雅的在java中统计代码块耗时;

/**
 * 1.7实现代码时长统计，需要配合try with resource 方式使用
 * @author vivi20
 * @ClassName Cost
 * @Date 2020/3/5 15:15
 * @Vertion 1.0
 */
public class Cost implements AutoCloseable{
    private long start;

    public Cost() {
        this.start = System.currentTimeMillis();
    }

    @Override
    public void close(){
        System.out.println("Cost:"+(System.currentTimeMillis() - start));
    }

    public static void testPrint() {
        for (int i = 0; i < 5; i++) {
            System.out.println("now " + i);
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //测试抛出异常时是否一样执行
//            if (i == 3) {
//                throw new RuntimeException("some exception!");
//            }

        }
    }

    public static void main(String[] args) {
        try(Cost cost = new Cost()) {
            testPrint();
        }
        System.out.println("------over-------");
    }
}
